<template>
	<div>
		<div class="upload">
			<div v-if="props.type !== 1">
				<template v-if="!changeImageUrl">
					<n-upload accept=".png,.jpg,.jpeg" @before-upload="onbeforeUpload">
						<n-upload-dragger>
							<div class="upload-box">
								<div>
									<img src="~@/assets/images/addBanner/icon_addad_upload.png" alt="" />
								</div>
								<p>上传图片</p>
							</div>
						</n-upload-dragger>
					</n-upload>
				</template>
				<img v-else class="upload-box" :src="changeImageUrl" />
				<p class="tips">要求：仅支持png、jpg格式，尺寸{{ props.width }}*{{ props.height }}（px）</p>
			</div>
			<div v-else>
				<div style="display: flex; align-items: flex-end">
					<div v-if="changeImageUrl">
						<img class="upload-card-img" :src="changeImageUrl" />
					</div>
					<n-upload
						v-if="!changeImageUrl"
						list-type="image-card"
						accept=".png,.jpg,.jpeg"
						@before-upload="onbeforeUpload"
					>
						<div class="upload-card">
							<img class="upload-card-icon" src="~@/assets/images/icon_up_img@2x.png" />
							<span style="">点击上传</span>
						</div>
					</n-upload>
					<n-upload
						v-else
						style="
							height: 18px;
							font-size: 12px;
							color: #1d6fe9;
							margin-left: 15px;
							cursor: pointer;
						"
						accept=".png,.jpg,.jpeg"
						@before-upload="onbeforeUpload"
					>
						重新上传
					</n-upload>
				</div>
				<p class="tips">要求：仅支持png、jpg格式，尺寸{{ props.width }}*{{ props.height }}（px）</p>
			</div>
			<n-modal
				v-model:show="showModal"
				title="图片裁剪"
				preset="card"
				:show-icon="false"
				:mask-closable="false"
				style="width: 800px"
			>
				<div>
					<div class="upload-btn">
						<n-button @click="clear">重新上传</n-button>
						<n-button style="margin-left: 6px" type="info" @click="finish">确认裁剪</n-button>
					</div>
				</div>
				<div class="cropper-content">
					<div
						class="cropper"
						:style="{
							width: props.width + 'px',
							height: props.height + 'px'
						}"
					>
						<VuePictureCropper
							style="width: 100%; height: 100%"
							:img="option.img"
							:options="{
								viewMode: 1,
								dragMode: 'move',
								aspectRatio: props.width / props.height,
								cropBoxResizable: false
							}"
							:preset-mode="{
								mode: 'fixedSize',
								width: props.width,
								height: props.height
							}"
						></VuePictureCropper>
					</div>
				</div>
			</n-modal>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue';
import VuePictureCropper, { cropper } from 'vue-picture-cropper'; //引入依赖
import { upload } from '@/api/banner';
import axios from 'axios';
import baseConfig from '@/config';
import { getQueryParam } from '@/utils/index';
const changeImageUrl = ref(''); //裁剪后上传的照片
const type = ref(1);
const option = reactive({
	img: ''
});
const props = defineProps({
	width: {
		typeof: Number,
		default: 750
	},
	height: {
		typeof: Number,
		default: 522
	},
	type: {
		typeof: Number,
		default: 1
	}
});

const showModal = ref(false);
const emit = defineEmits(['commit']);

const clear = () => {
	showModal.value = false;
	option.img = '';
	changeImageUrl.value = '';
};
const finish = async () => {
	// 裁切后会按照该尺寸生成结果
	const file = await cropper.getFile();
	let param = new FormData(); // 创建form对象
	param.append('file', file); // 通过append向form对象添加数据

	confirmUpload(param);
};
const confirmUpload = (file) => {
	let config = {
		// 添加请求头
		headers: {
			Authorization: getQueryParam('token') ? getQueryParam('token') : baseConfig.LL_APP_TOKEN
		}
	};
	let url = `${baseConfig.BASE_URL}/anchor/platform/anchors/common/upload`;
	axios.post(url, file, config).then((res) => {
		if (res.data.code !== 200) return;
		clear();
		changeImageUrl.value = res.data.data;
		emit('commit', changeImageUrl.value);
	});
};
const onbeforeUpload = ({ file }) => {
	let reader = new FileReader();
	reader.onload = (e) => {
		const data = e.target.result;
		//加载图片获取图片真实宽度和高度
		const image = new Image();
		image.onload = () => {
			const width = image.width;
			const height = image.height;
			if (width === props.width && height === props.height) {
				let param = new FormData(); // 创建form对象
				param.append('file', file.file); // 通过append向form对象添加数据
				confirmUpload(param);
			} else {
				nextTick(() => {
					option.img = data;
					showModal.value = true;
				});
			}
		};
		image.src = data;
	};
	reader.readAsDataURL(file.file);
	return false;
};

defineExpose({ changeImageUrl });
</script>

<style lang="less" scoped>
.upload-btn {
	display: flex;
	justify-content: center;
	margin: 0px 0 20px 0;
}
.upload {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	&-title {
		margin-bottom: 16px;
		font-size: 16px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #333333;
	}
	&-box {
		width: 376px;
		height: 140px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		img {
			width: 36px;
			height: 36px;
		}
		font-size: 14px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #999999;
	}
	&-card {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #333333;
		&-icon {
			width: 24px;
			height: 24px;
		}
		&-img {
			width: 120px;
			height: 80px;
		}
	}
	.tips {
		margin-top: 10px;
		font-size: 12px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #f5894e;
	}
}
</style>
